package com.example.student_blocket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MyAdsActivity extends Activity {

	private final String LOAD_MY_ADS = Singleton.getInstance().getHOST() + "shop-app/my-ads.php";
	private ArrayList<AdsListDetails> ads_list;
	private ListView listView;
	private Misc misc = new Misc();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.my_ads_activity);
		iniGUIComponents();
		new LoadAds().execute();
	}

	private void iniGUIComponents() {
		ads_list = new ArrayList<AdsListDetails>();
		listView = (ListView) findViewById(R.id.listMyAds);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				AdsListDetails opas = ads_list.get(position);
				String selectedID = opas.getId();
				Intent intent = new Intent(MyAdsActivity.this, MyAdsDetail.class);
				finish();
				intent.putExtra("id", selectedID);
				startActivity(intent);
			}
		});
	}
	@Override
	public void onBackPressed() {
		startActivity(new Intent(MyAdsActivity.this, UserProfileActivity.class));
		finish();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.about_us, menu);
		return true;
	}
	
	private class LoadAds extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(MyAdsActivity.this);
	        pDialog.setMessage("Loading Ads...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
		@Override
		protected Boolean doInBackground(String... params) {
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
			values.add(new BasicNameValuePair("username", Singleton.getInstance().getUsername()));
            JSONObject json = jParser.makeHttpRequest(LOAD_MY_ADS, values);
            try {
                int success = json.getInt("affected");
 
                if (success == 1) {
                	JSONArray ads = json.getJSONArray("ads");
                	
                    for (int i = 0; i < ads.length(); i++) {
                        JSONObject c = ads.getJSONObject(i);
 
                        String id = "" + c.getInt("id");
                        String title = c.getString("title");
                        String price = c.getString("price");
                        String image = c.getString("image");
                        String date = c.getString("date");
                        String category = c.getString("category");
                        String description = c.getString("description");
                        String owner = c.getString("owner");
                        
                        Bitmap imageBitmap = misc.getImage(image);
						
                        AdsListDetails adsDetails = new AdsListDetails(id, title, price, category, date, imageBitmap, description, owner);
                        ads_list.add(adsDetails);
                    }
                    return true;
                } else {
                    return false;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
		@Override
		protected void onPostExecute(Boolean op) {
			pDialog.dismiss();
            if (op) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Adapter adapter = new Adapter(getApplicationContext(),
								ads_list);
						listView.setAdapter(adapter);
					}
				});
			} else {
				misc.showErrorMessage("You do NOT have any Ads!", getApplicationContext());
				Thread timeOut = new Thread(){
					@Override
					public void run(){
						try{
							sleep(2000);
						}catch (InterruptedException e){
							e.printStackTrace();
						}finally{
							Intent intent = new Intent(getApplicationContext(), UserProfileActivity.class);
							startActivity(intent);
							finish();
						}
					}
				};
				timeOut.start();
			}
        }
	}

}
